﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


namespace Web.Views.Admin.Controls.News
{
    public partial class NewsGridControl : System.Web.UI.UserControl
    {

        public const string DefaultTargetUrl = "~/Views/Admin/TT_News/Edit.aspx";

        private string _targetUrl;

        [System.ComponentModel.DefaultValue(DefaultTargetUrl)]
        public string TargetUrl
        {
            get
            {
                return _targetUrl;
            }
            set
            {
                _targetUrl = value;
            }
        }

        protected string[] FilterInfo
        {
            get
            {
                return ((string[])(Session[(UniqueID + Request.Path)]));
            }
            set
            {
                Session[(UniqueID + Request.Path)] = value;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            _targetUrl = DefaultTargetUrl;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsCallback)
                ApplyDataFilter();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ((HyperLinkField)(GridView1.Columns[0])).DataNavigateUrlFormatString = String.Format("{0}?NewsID={{0}}", TargetUrl);
            ApplyDataFilter();
        }

        protected void ShowFilterLink_Click(object sender, EventArgs e)
        {
            ShowDataFilter(true);
        }

        protected void CancelFilterLink_Click(object sender, EventArgs e)
        {
            FilterInfo = null;
            ShowDataFilter(false);
        }

        protected void ApplyFilterLink_Click(object sender, EventArgs e)
        {
            FilterInfo = new string[] {
                FilterField.SelectedValue,
                FilterValue.Text};
        }

        private void ShowDataFilter(bool show)
        {
            ShowFilterTask.Visible = !(show);
            FilterTable.Visible = show;
            if (show)
                FilterValue.Focus();
        }

        private void ApplyDataFilter()
        {
            string filterExpression = null;
            string[] filter = FilterInfo;
            if (filter != null)
            {
                // select the field in the filter field drop down
                string[] fieldInfo = filter[0].Split(',');
                FilterField.Items.FindByValue(filter[0]).Selected = true;
                FilterValue.Text = filter[1];
                // create a filter
                StringBuilder sb = new StringBuilder();
                bool first = true;
                bool booleanOr = true;
                Match m = Regex.Match(filter[1], "\\s*(?\'Operation\'<(=|>){0,1}|>={0,1}){0,1}\\s*(?\'Value\'[\\s\\S]+?)\\s*(,|$)", RegexOptions.Compiled);
                while (m.Success)
                {
                    if (first)
                        first = false;
                    else
                        sb.Append("or");
                    string operation = m.Groups["Operation"].Value;
                    if (String.IsNullOrEmpty(operation))
                        if (fieldInfo[1] == "String")
                            operation = "like";
                        else
                            operation = "=";
                    if (operation != "like" && !((operation == "=")))
                        booleanOr = false;
                    string sampleValue = m.Groups["Value"].Value.Replace("\'", "\'\'");
                    if (operation == "like")
                        sampleValue = (sampleValue + "%");
                    if (fieldInfo[1] == "String")
                        sampleValue = String.Format("\'{0}\'", sampleValue);
                    if (fieldInfo[1] == "DateTime")
                        sampleValue = String.Format("#{0}#", sampleValue);
                    sb.AppendFormat("([{0}]{1} {2})", fieldInfo[0], operation, sampleValue);
                    m = m.NextMatch();
                }
                filterExpression = sb.ToString();
                if (!(booleanOr))
                    filterExpression = filterExpression.Replace(")or(", ")and(");
            }
            if (SqlDataSource1.FilterExpression != filterExpression)
            {
                try
                {
                    SqlDataSource1.FilterExpression = filterExpression;
                    GridView1.DataBind();
                }
                catch (Exception)
                {
                    SqlDataSource1.FilterExpression = String.Empty;
                }
                if (!(String.IsNullOrEmpty(filterExpression)))
                    ShowDataFilter(true);
            }
        }
    }
}